<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
  * Licence Agreement
  *
  */

/**
  * Blog Controller
  *
  */

class Controller_Blog extends Controller_Template_Default {

  /**
   * Blog Index Page
   *
   */
  public function action_index()
  {
	
	if (isset($_GET['edit']))
	{
		$edit = Security::xss_clean($_GET['edit']);
	}
	else
	{
		$edit = 0;
	}
	
	// Check if the user is logged in
	if (!Auth::instance()->logged_in())
	{
		// Attempt to auto-login the user, if they have chosen that option
		Auth::instance()->auto_login();
	}
	
	// logon / logoff links
  	if (Auth::instance()->logged_in())
  	{
		$user_link = HTML::anchor('user/logoff', __('Logoff'), array('rel' => 'shadowbox;width=645;height=290',
																	 'title' => 'Login / Signup'));
  	}
  	else
  	{
		$user_link = HTML::anchor('user/login', __('Login'), array('rel' => 'shadowbox;width=645;height=290',
																   'title' => 'Login / Signup'));
  	}
	
	// get the user id from the session data
	$user = Session::instance()->get('auth_user', NULL);
	
//	if (isset($user))
//	{
//		$user_role = TRUE;
//	}
//	else
//	{
//		$user_role = FALSE;
//	}
	
	// set template headers
	$this->template->set('title', __('Blog'));
    $this->template->set('header_text', __('Blog'));
	
	// get the latest post
	$post = DB::select('id',
					   'author',
					   'date',
					   'edit',
					   'content',
					   'title',
					   'tags')
				->from('posts')
				->order_by('id', 'DESC')
				->limit(1)
				->execute()
				->current();

	$post_id = $post['id'];
	
	// get the comments for the post 
	$comments = DB::select('comments.id',
						   'comments.author',
						   'comments.date',
						   'comments.edit',
						   'comments.status',
						   'comments.content',
						   'userdetails.firstname',
						   'userdetails.lastname')
				->from('comments')
				->join('userdetails','right')
				->on('comments.author','=','userdetails.user')
				->where('post','=',$post_id)
				->order_by('comments.id', 'ASC')
				->execute()
				->as_array();
	
   	// set templates
	
	// blog template
	$this->template->set('content', new View('blog/blog_view'));

	// template content depends on user role
	//if (isset($user_role))
  	if (Auth::instance()->logged_in())
	{
//		$this->template->set('post', new View('blog/post_edit'));
		$this->template->set('post', new View('blog/post_view'));
		$this->template->set('comment', new View('blog/comment_edit'));
		$this->template->set('comment_add', new View('blog/comment_add'));
	}
	else
	{
		$this->template->set('post', new View('blog/post_view'));
		$this->template->set('comment', new View('blog/comment_view'));
		$this->template->set('comment_add', new View('blog/comment_add_login'));
	}
	
	// bind data to post
	$this->template->post->bind('post', $post);

	// bind data to comments
   	$this->template->comment->bind('comments', $comments);
	$this->template->comment->bind('user', $user);
	$this->template->comment->bind('edit', $edit);

	// bind data to add comments
	$this->template->comment_add->bind('post', $post);
	$this->template->comment_add->bind('comment', $comments);
	$this->template->comment_add->bind('user', $user);
	
	// bind data to blog
	$this->template->content->bind('errors', $errors);
   	$this->template->content->bind('user_link', $user_link);
   	$this->template->content->bind('post', $this->template->post);
   	$this->template->content->bind('comments', $this->template->comment);
	$this->template->content->bind('comment_add', $this->template->comment_add);
	
  }

  /**
   * Add a comment
   *
   */
  public function action_comment_add()
  {
	$errors = array();
	
	// no direct access
    if (!isset($_POST['submit']))
	{
		Request::instance()->redirect('blog/index');
	}

    if (isset($_POST['submit']))
    {
      // Assign values from _POST individually to prevent malicious form submission
      // NOTE: Future versions of Sprig may allow limitation to 'editable' fields only, in which case this step will be un-necessary
    	$comment = Sprig::factory('comment')
    	          ->values(array('id'		=> NULL,
								 'post'		=> $_POST['post'],
    	                         'author'	=> $_POST['author'],
								 'date'		=> $_SERVER['REQUEST_TIME'],
								 'edit'		=> NULL,
								 'status'	=> 'approved',
    	                         'content'	=> $_POST['content']));

      try
      {
        // Add the comment
        $comment->create();
		
        // Redirect to blog index page
        Request::instance()->redirect('blog/index');
    	}
    	catch (Validate_Exception $e)
    	{
    	  $errors = $e->array->errors('comment');
   	  }
    }
  }

  /**
   * Edit a comment
   *
   */
  public function action_comment_edit()
  {
	$errors = array();
	
	// no direct access
    if (!isset($_POST['submit']))
	{
		Request::instance()->redirect('blog/index');
	}

    if (isset($_POST['submit']))
    {
		$this->template->set('title', __('Log On'));
		$this->template->set('header_text', __('Log On'));
		$this->template->set('content', __('Hello'));
		
	  try
	  {
		$total_rows = DB::update('comments')
						->set(array('edit'		=> $_SERVER['REQUEST_TIME'],
									'content'	=> Security::xss_clean($_POST['content_edit'])))
						->where('id','=',$_POST['comment_id'])
						->execute();
        
		Request::instance()->redirect('blog/index');
	  }
	  catch( Database_Exception $e )
	  {
		 echo $e->getMessage();
	  }
	}
  }

  /**
   * Allow the user to login
   *
   */
  public function action_login() {
    if (Auth::instance()->auto_login())
    {
      // The user is already logged in so just send them to the account index page.
      Request::instance()->redirect('user/index');
    }

    $errors = array();
    $this->template->set('title', __('Log On'));
    $this->template->set('header_text', __('Log On'));
   	$this->template->set('content', new View('user/login'));
   	$this->template->content->bind('fields', $_POST);
   	$this->template->content->bind('errors', $errors);

   	// ensure that a token was submitted and matches the token in the session, provides some basic security against CSFR
    if (isset($_POST['submit']) && (empty($_POST['token']) || $_POST['token'] !== $this->session->get('token')))
    {
      $errors[] = __('Form token not set or invalid');
      unset($_POST['submit']);
    }
    unset($_POST['token']);

    $token = Security::token();
    $this->session->set('token', $token);
    $this->template->content->set('token', $token);

    if (isset($_POST['submit']))
    {
      if (Arr::get($_POST,'new_user') === 'true')
      {
        unset($_POST['submit']);
      	Request::instance()->response = Request::factory('user/create')
      	                                   ->execute();
        $this->auto_render = FALSE;
      }
      else
      {
        $remember = Arr::get($_POST, 'remember_me') == 'on' ? TRUE : FALSE;
        if ( Auth::instance()->login($_POST['email'], $_POST['password'], $remember) )
      	{
      	  Request::instance()->redirect('user/index');
      	}
      	else
      	{
      	 $errors[] = __('Sorry, but we were unable to confirm your email address and / or password. Please check and try again.');
      	}
      }
    }
  }
}